/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2024-2024. All rights reserved.
 */


import path from 'path';

import { expect } from '@jest/globals';
import fse from 'fs-extra';

import { initExecuteCommand, runHvigorAsync  } from '../../common/common';
import {
  AbilityType,
  APIType,
  APIVersion,
  CaseLevel, IsEnable,
  LanguageType,
  ModuleTemplateType,
  RuntimeOSType,
  SDKType,
  SignType,
} from '../../plugins/project-builder/models/constants';
import {TestCaseBuilder} from '../../plugins/task-builder/task-case-builder';
import {ProjectBuildOption, TestCaseFun} from '../../plugins/task-builder/test-case';
import {TestTaskOption, TestTaskOptionBuilder} from '../../plugins/task-builder/test-task-option';

/**
 * 测试工程选项
 *
 * @type {{template: ProjectTemplateOption}}
 */
const projectBuilderOption: ProjectBuildOption = {
  template: {
    sdk: SDKType.Single,
    runtimeOS: RuntimeOSType.HarmonyOS,
    apiVersion: APIVersion.API10,
    apiType: APIType.STAGE,
    language: LanguageType.ArkTs,
    abilityType: AbilityType.Application,
    entryTemplateType: ModuleTemplateType.EmptyAbility
  },
};

const testTaskOption: TestTaskOption = TestTaskOptionBuilder.builder().caseLevel(CaseLevel.L2).sign(SignType.NoSign).ohpmInstall(IsEnable.Enable).build();

/**
 * 测试函数
 *
 * @param {Project} project 测试工程对象
 * @param {TestTaskOption} taskConfig 测试操作可选项
 * @param {ICaseRecord} record 测试记录
 * @return {Promise<void>}
 */
const testFun: TestCaseFun = async (project, taskConfig, record) => {
  // 测试工程主目录路径
  const projectRoot = project.projectRootPath();

  // 检查有没有report文件夹， 没有则添加
  const reportDirPath = path.resolve(`${projectRoot}/.hvigor/report`);
  if (!fse.existsSync(reportDirPath)) {
    fse.mkdirSync(reportDirPath, {recursive: true});
  }

  // 读取 JSON 文件
  const jsonData = JSON.parse(fse.readFileSync(`${projectRoot}/hvigor/hvigor-config.json5`, 'utf-8'));

  if (!jsonData.execution) {
    jsonData.execution = {}; // 如果不存在则初始化为一个空对象
  }

  // 设置 analyze 字段
  jsonData.execution.analyze = false;
  fse.writeFileSync(`${projectRoot}/hvigor/hvigor-config.json5`, JSON.stringify(jsonData, null, 2), 'utf-8');

  // 计算文件数量方法
  const countFilesInDirectory = (directoryPath: string): number => {
    let fileCount = 0;

    // 读取目录内容
    const items = fse.readdirSync(directoryPath);

    items.forEach(item => {
      const itemPath = path.join(directoryPath, item);
      const stats = fse.statSync(itemPath);

      // 如果是文件，则计数
      if (stats.isFile()) {
        fileCount++;
      }
    });

    return fileCount;
  };
    // 计算编译前文件数量
  const beforeBuildReportNumber = countFilesInDirectory(reportDirPath);
  // 需要执行的命令行参数
  const commands = initExecuteCommand({
    mode: 'project',
    product: 'default',
    tasks: 'assembleApp',
    daemon: false,
  });

  commands.push('--verbose-analyze');

  // 执行编译
  const result = await runHvigorAsync(projectRoot, commands);
  // 计算编译后文件数量
  const afterBuildReportNumber = countFilesInDirectory(reportDirPath);

  // 记录测试日志
  record.addStep('Build App', result);

  // 使用断言判断执行结果

  expect(result.stdout).toContain('Finished :entry:default@SignHap');
  expect(result.stdout).toContain('Finished ::SignApp');
  expect(result.stdout).toContain('BUILD SUCCESSFUL');

  // FOR AR20241025269911 this line is changed
  expect(beforeBuildReportNumber).toBe(afterBuildReportNumber - 2);
};


// 将demo测试用例注册到测试用例中心
TestCaseBuilder.builder()
  .caseName('DTS2024102803899')
  .description('命令行旧版参数生成report')
  .projectBuilderOption(projectBuilderOption)
  .taskConfig(testTaskOption)
  .testFun(testFun)
  .load();